﻿#region Using Region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;
using System.IO;
using System.Configuration;
using ICE.Vacations.Entidades;

#endregion

namespace ICE.Vacations.Datos.FileManager
{
    public static class Logger
    {
        //
        public enum MessageType { Information, Error, Warning }
        /// <summary>
        /// Decode Error codes.
        /// </summary>
        /// <param name="ErrorType"></param>
        /// <returns></returns>
        private static String ErrorMessage(MessageType ErrorType)
        {
            switch (ErrorType)
            {
                case MessageType.Error:
                    return "Error Message";
                case MessageType.Information:
                    return "Information Message";
                case MessageType.Warning:
                    return "Warning Message";

                default:
                    return "Tipo de error inesperado" + ErrorType;
            }
        }




        /// <summary>
        /// Write Logs in File System
        /// </summary>
        /// <param name="message"></param>
        /// <param name="appConfig"></param>
        public static void fileWrite(string message, MessageType type)
        {
            int _logCounter = 0;
            string logFilename = Config.logLocation + "\\" + Config.logPrefix + "-" + DateTime.Now.ToString("yyyyMMdd") + ".Log";

            if (!(Directory.Exists(Config.logLocation)))
                Directory.CreateDirectory(Config.logLocation);
            try
            {
                using (StreamWriter swLocalLog = new StreamWriter(logFilename, true))
                {
                    swLocalLog.WriteLine(messageToFile(type, message));
                    swLocalLog.Flush();
                }

                FileInfo fileProps = new FileInfo(logFilename);
                if (fileProps.Length > (Convert.ToInt32(Config.logMaxSizeBytes) * 1000))
                {
                    while (true)
                        try
                        {
                            File.Move(logFilename, logFilename + _logCounter.ToString() + ".old");
                            break;
                        }
                        catch { _logCounter++; }
                }
            }

            catch (Exception exc)
            {
                throw new Exception("Imposible escribir en el logFile " + exc.Message);
            }

        }


        private static string messageToFile(MessageType error, string description)
        {
            return DateTime.Now.ToString("yyyy'-'MM'-'dd HH':'mm':'ss':'fff") + " - " + Logger.ErrorMessage(error) + " - " + description + "\r\n";
        }
    }
}